/*
 * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.kyd.jpa.uid.baidu.worker.dao;

import com.kyd.jpa.uid.baidu.worker.entity.WorkerNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * DAO for M_WORKER_NODE
 *
 * @author yutianbao
 */
public class WorkerNodeDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * Get {@link WorkerNode} by node host
     *
     * @param host
     * @param port
     * @return
     */
    public WorkerNode getWorkerNodeByHostPort(String host, String port) {
        final WorkerNode workerNode = new WorkerNode();
        String querySql = "select * from worker_node where host_name = ? and port = ? ";
        this.jdbcTemplate.query(querySql, new String[] {host, port}, rs -> {
            workerNode.setId(rs.getLong("id"));
            workerNode.setHostName(rs.getString("host_name"));
            workerNode.setPort(rs.getString("port"));
            workerNode.setType(rs.getInt("type"));
            workerNode.setLaunchDateDate(rs.getDate("launch_date"));
            workerNode.setModified(rs.getDate("modified_time"));
            workerNode.setCreated(rs.getDate("created_time"));
        });
        return workerNode;
    }

    /**
     * Add {@link WorkerNode}
     *
     * @param workerNode
     */
    public void addWorkerNode(WorkerNode workerNode) {
        String sql = "insert into worker_node(host_name, port, type, launch_date, modified_time, created_time) " + " values (?, ?, ?, ?, now(), now())";
        this.jdbcTemplate.update(sql, new Object[] {workerNode.getHostName(), workerNode.getPort(), workerNode.getType(), workerNode.getLaunchDate()});
    }

}
